package com.chukun.interview.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chukun
 * @version 1.0.0
 * @description 树的遍历基本操作
 * @createTime 2023年05月09日 23:50:00
 */
public class TreeTraversalOperator {

    /**
     * 二叉树的前序遍历
     * @param root
     * @return
     */
    public List<Integer> preorderTraversal(TreeNode root) {
      List<Integer> res = new ArrayList<>();
      _preorderTraversal(root, res);
      return res;
    }

    private void _preorderTraversal(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        res.add(root.val);
        if (root.left !=null) {
            _preorderTraversal(root.left, res);
        }
        if (root.right !=null) {
            _preorderTraversal(root.right, res);
        }
    }

    /**
     * 二叉树的中序遍历
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        _inorderTraversal(root, res);
        return res;
    }

    private void _inorderTraversal(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        if (root.left !=null) {
            _inorderTraversal(root.left, res);
        }
        res.add(root.val);
        if (root.right !=null) {
            _inorderTraversal(root.right, res);
        }
    }

    /**
     * 二叉树的后序遍历
     * @param root
     * @return
     */
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        _postorderTraversal(root, res);
        return res;
    }

    private void _postorderTraversal(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        if (root.left !=null) {
            _postorderTraversal(root.left, res);
        }
        if (root.right !=null) {
            _postorderTraversal(root.right, res);
        }
        res.add(root.val);
    }
}



class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
